package com.kele.controller;

import com.kele.domain.User;
import com.kele.service.FileService;
import com.kele.utils.ResponseData;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 创作人 王箫凯
 * Date 2021/5/24
 * Time 14:30
 *
 * @author 王箫凯
 */


@RestController
@RequestMapping(value = "/file")

public class FileController {
    @ResponseBody
    @RequestMapping(value = "/upLOad",method = RequestMethod.POST)
    public ResponseData upLoad(HttpServletRequest request , MultipartFile upload) throws Exception {
        //获取文件的类型
        String type=request.getParameter("type");
        //设置文件上传的路径
        String path="E:/xiazai/"+type;
        //设置文件名称
        String filename = upload.getOriginalFilename();
        //获取文件的后缀名：
        String suffix=filename.substring(filename.lastIndexOf("."));
        //组合新的文件ID
        String newName= UUID.randomUUID().toString()+suffix;
        File file=new File(path);
        //如果文件路径不存在，就创建一个新的文件路径
        if (!file.exists()){
            file.mkdirs();
        }
        //文件写入
        // 将读取到的文件写入到路径为path 的newName文件中
        upload.transferTo(new File(path,newName));

        //获取session  从Session中获取此时的用户对象
        User user= (User) request.getSession().getAttribute("account");
        //容器的调用，避免了容器的重复创建，造成了内存的损耗
        WebApplicationContext context=null;
        ServletContext servletContext= request.getServletContext();
        context= WebApplicationContextUtils.getWebApplicationContext(servletContext);
        //动态代理
        FileService fileService= (FileService) context.getBean("upLoad");
        //调用方法，将信息上传到数据库中
        String thePath=path+"/"+newName;
        int nums=fileService.upLoad(thePath,user.getAccount());
        if(nums!=1){
            return ResponseData.fail("错误，上传失败");
        }else {
            return ResponseData.success("上传成功");
        }
    }
}
